package LeetCode_SingleLinkedlist;

/**
 * Created with IntelliJ IDEA.
 * Description:判断链表是否有环
 * User: 阿宾
 * Date: 2024-11-11
 * Time: 09:40
 */
public class Demo8 {
    static class ListNode {
        int val;
        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static boolean hasCycle(ListNode head) {
        if(head == null || head.next == null){
            return false;
        }
        //方法1
        /*ListNode slow = head;
        ListNode fast = head.next;
        while(slow != fast){
            if(fast == null ||fast.next == null){
                return false;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        return true;*/
        //方法2
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null){

            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        l1.next = l2;
        boolean ret = hasCycle(l1);
        System.out.println(ret);
    }
}
